package com.li.interseptor;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.li.result.Result;
import com.li.util.BeanContent;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.Instant;

/**
 * @Author: zhiqingLi
 * @Description:
 * @Date: Created in 10:22 2024/3/13
 **/
@Component
public class JWTInterceptor implements HandlerInterceptor {
    @Value("${li}")
    private String secret;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("拦截器起作用了");
        //从请求头中获取 token
        String token = request.getHeader("token");
        try {
            DecodedJWT verify = JWT.require(Algorithm.HMAC256(secret)).build().verify(token);//校验令牌
            Integer companyId = verify.getClaim("companyId").asInt();
            System.out.println(companyId);
            BeanContent.setCurrentId(companyId);
            return true;
        }catch (Exception e){
            Result.error("令牌已过期或解析错误请重新登录");
            return false;
        }

    }
}
